package com.atguigu.gulimall.product.service.impl;

import com.atguigu.common.constant.ProductConstat;
import com.atguigu.common.utils.DataUtil;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.atguigu.gulimall.product.dao.AttrDao;
import com.atguigu.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.atguigu.gulimall.product.entity.AttrEntity;
import com.atguigu.gulimall.product.entity.AttrGroupEntity;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.entity.vo.AttrGroupRelationVo;
import com.atguigu.gulimall.product.entity.vo.AttrRespVo;
import com.atguigu.gulimall.product.entity.vo.AttrVo;
import com.atguigu.gulimall.product.service.AttrAttrgroupRelationService;
import com.atguigu.gulimall.product.service.AttrGroupService;
import com.atguigu.gulimall.product.service.AttrService;
import com.atguigu.gulimall.product.service.CategoryService;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    private AttrAttrgroupRelationService attrAttrgroupRelationService;

    @Autowired
    private AttrAttrgroupRelationDao relationDao;

    @Autowired
    private AttrGroupService attrGroupService;

    @Autowired
    private CategoryService categoryService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveAttr(AttrVo attrVo) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrVo, attrEntity);
        this.save(attrEntity);
        //保存关联关系
        if (attrEntity.getAttrType() == ProductConstat.AttrEnum.ATTR_TYPE_BASE.getCode()
                && DataUtil.isNotEmpty(attrVo.getAttrGroupId())) {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrId(attrEntity.getAttrId());
            relationEntity.setAttrGroupId(attrVo.getAttrGroupId());
            attrAttrgroupRelationService.save(relationEntity);
        }
    }

    @Override
    public PageUtils queryBaseAttrPage(Map<String, Object> params, Long catelogId, String attrType) {
        String key = (String) params.get("key");
        Wrapper<AttrEntity> wrapper = new LambdaQueryWrapper<AttrEntity>()
                .eq(catelogId.intValue() != 0, AttrEntity::getCatelogId, catelogId)
                .eq(AttrEntity::getAttrType, "base".equalsIgnoreCase(attrType) ? ProductConstat.AttrEnum.ATTR_TYPE_BASE.getCode() : ProductConstat.AttrEnum.ATTR_TYPE_SALE.getCode())
                .and(DataUtil.isNotEmpty(key), (obj) -> {
                    obj.eq(AttrEntity::getAttrId, key).or().like(AttrEntity::getAttrName, key);
                });
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );
        PageUtils pageUtils = new PageUtils(page);
        List<AttrEntity> records = page.getRecords();
        if (DataUtil.isNotEmpty(records)) {
            List<AttrRespVo> collect = records.stream().map((record) -> {
                AttrRespVo attrRespVo = new AttrRespVo();
                BeanUtils.copyProperties(record, attrRespVo);
                AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationService
                        .getOne(new LambdaQueryWrapper<AttrAttrgroupRelationEntity>().eq(AttrAttrgroupRelationEntity::getAttrId, record.getAttrId()));
                if (DataUtil.isNotEmpty(relationEntity) && DataUtil.isNotEmpty(relationEntity.getAttrGroupId())) {
                    AttrGroupEntity attrGroupEntity = attrGroupService.getById(relationEntity.getAttrGroupId());
                    if (DataUtil.isNotEmpty(attrGroupEntity)) {
                        attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                    }
                }
                CategoryEntity categoryEntity = categoryService.getById(record.getCatelogId());
                if (DataUtil.isNotEmpty(categoryEntity)) {
                    attrRespVo.setCatelogName(categoryEntity.getName());
                }
                return attrRespVo;
            }).collect(Collectors.toList());
            pageUtils.setList(collect);
        }
        return pageUtils;
    }

    @Override
    public AttrRespVo getAttrInfo(Long attrId) {
        AttrRespVo attrRespVo = new AttrRespVo();
        AttrEntity entity = this.getById(attrId);
        BeanUtils.copyProperties(entity, attrRespVo);

        if (entity.getAttrType() == ProductConstat.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationService
                    .getOne(new LambdaQueryWrapper<AttrAttrgroupRelationEntity>().eq(AttrAttrgroupRelationEntity::getAttrId, attrId));
            if (DataUtil.isNotEmpty(relationEntity)) {
                AttrGroupEntity attrGroupEntity = attrGroupService.getById(relationEntity.getAttrGroupId());
                if (DataUtil.isNotEmpty(attrGroupEntity)) {
                    attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                    attrRespVo.setAttrGroupId(attrGroupEntity.getAttrGroupId());
                }
            }
        }


        Long catelogId = entity.getCatelogId();
        Long[] catelogPath = categoryService.findCatelogPath(catelogId);
        attrRespVo.setCatelogPath(catelogPath);
        CategoryEntity categoryEntity = categoryService.getById(catelogId);
        if (DataUtil.isNotEmpty(categoryEntity)) {
            attrRespVo.setCatelogName(categoryEntity.getName());
        }
        return attrRespVo;
    }

    @Transactional
    @Override
    public void updateAttr(AttrVo attrVo) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrVo, attrEntity);
        this.updateById(attrEntity);

        if (attrEntity.getAttrType() == ProductConstat.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            //保存关联关系
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrId(attrEntity.getAttrId());
            relationEntity.setAttrGroupId(attrVo.getAttrGroupId());
            LambdaQueryWrapper<AttrAttrgroupRelationEntity> wrapper = new LambdaQueryWrapper<AttrAttrgroupRelationEntity>()
                    .eq(AttrAttrgroupRelationEntity::getAttrId, attrVo.getAttrId());
            if (!attrAttrgroupRelationService.update(relationEntity, wrapper)) {
                attrAttrgroupRelationService.save(relationEntity);
            }
        }

    }

    @Override
    public List<AttrEntity> getRelationAttr(Long attrgroupId) {
        LambdaQueryWrapper<AttrAttrgroupRelationEntity> wrapper = new LambdaQueryWrapper<AttrAttrgroupRelationEntity>()
                .eq(AttrAttrgroupRelationEntity::getAttrGroupId, attrgroupId);
        List<AttrAttrgroupRelationEntity> relationEntityList = attrAttrgroupRelationService.list(wrapper);
        if (DataUtil.isNotEmpty(relationEntityList)) {
            List<Long> attrIds = relationEntityList.stream().map((relationEntity) -> {
                return relationEntity.getAttrId();
            }).collect(Collectors.toList());
            List<AttrEntity> attrEntities = this.listByIds(attrIds);
            return attrEntities;
        }
        return null;
    }

    @Override
    public void relationdelete(AttrGroupRelationVo[] vos) {
//        LambdaQueryWrapper<AttrAttrgroupRelationEntity> wrapper = new LambdaQueryWrapper<AttrAttrgroupRelationEntity>()
//                .eq(AttrAttrgroupRelationEntity::getAttrId, attrgroupId)
//                .eq(AttrAttrgroupRelationEntity::getAttrGroupId,)

        List<AttrAttrgroupRelationEntity> collect = Arrays.asList(vos).stream().map((vo) -> {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(vo, relationEntity);
            return relationEntity;
        }).collect(Collectors.toList());
        relationDao.deleteBatchRelations(collect);
    }

    /**
     * 获取当前分组没有关联的所有属性
     *
     * @param params
     * @param attrgroupId
     * @return
     */
    @Override
    public PageUtils getNoRelationAttr(Map<String, Object> params, Long attrgroupId) {
        AttrGroupEntity groupEntity = attrGroupService.getById(attrgroupId);
        if (DataUtil.isNotEmpty(groupEntity)) {
            LambdaQueryWrapper<AttrGroupEntity> wrapper = new LambdaQueryWrapper<AttrGroupEntity>()
                    .eq(AttrGroupEntity::getCatelogId, groupEntity.getCatelogId());
            List<AttrGroupEntity> groupEntities = attrGroupService.list(wrapper);
            if (DataUtil.isNotEmpty(groupEntities)) {
                List<Long> groupIds = groupEntities.stream().map((item) -> {
                    return item.getAttrGroupId();
                }).collect(Collectors.toList());
                LambdaQueryWrapper<AttrAttrgroupRelationEntity> queryWrapper = new LambdaQueryWrapper<AttrAttrgroupRelationEntity>()
                        .in(AttrAttrgroupRelationEntity::getAttrGroupId, groupIds);
                List<AttrAttrgroupRelationEntity> relationEntities = attrAttrgroupRelationService.list(queryWrapper);
                List<Long> collect = new ArrayList<>();
                if (DataUtil.isNotEmpty(relationEntities)) {
                    collect = relationEntities.stream().map((item) -> {
                        return item.getAttrId();
                    }).collect(Collectors.toList());
                }
                String key = (String) params.get("key");
                LambdaQueryWrapper<AttrEntity> lambdaQueryWrapper = new LambdaQueryWrapper<AttrEntity>()
                        .eq(AttrEntity::getCatelogId, groupEntity.getCatelogId())
                        .eq(AttrEntity::getAttrType, ProductConstat.AttrEnum.ATTR_TYPE_BASE.getCode())
                        .notIn(DataUtil.isNotEmpty(collect), AttrEntity::getAttrId, collect)
                        .and(DataUtil.isNotEmpty(key), (obj) -> {
                            obj.eq(AttrEntity::getAttrId, key).or().like(AttrEntity::getAttrName, key);
                        });
                IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), lambdaQueryWrapper);
                PageUtils pageUtils = new PageUtils(page);
                return pageUtils;
            }
        }
        return null;
    }

    @Override
    public List<Long> selectSearchAttrIds(List<Long> attrIds) {
        LambdaQueryWrapper<AttrEntity> wrapper = new LambdaQueryWrapper<AttrEntity>()
                .in(AttrEntity::getAttrId, attrIds)
                .eq(AttrEntity::getSearchType, 1);
        List<AttrEntity> list = this.list(wrapper);
        if (DataUtil.isNotEmpty(list)) {
            List<Long> collect = list.stream().map(i -> {
                return i.getAttrId();
            }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }
}
